package items

import (
	"server/game/cache"
	"server/share/config"

	"github.com/hwcer/cosgo/registry"
	"github.com/hwcer/yyds/context"
	"github.com/hwcer/yyds/errors"
)

func init() {
	context.Register(&items{})
}

const itemsUseMaxNum = 100

// items 道具操作
type items struct {
}

func (this *items) Caller(node *registry.Node, handle *context.Context) interface{} {
	f := node.Method().(func(*items, *context.Context) interface{})
	return f(this, handle)
}

// Use 道具使用
func (this *items) Use(c *context.Context) interface{} {
	args := &Args{}
	if err := c.Bind(args); err != nil {
		return err
	}
	if args.Key == "" {
		return errors.ErrArgEmpty
	}
	if args.Num <= 0 {
		return c.Error("num error")
	}
	if args.Num > itemsUseMaxNum {
		args.Num = itemsUseMaxNum
	}
	itemsColl := cache.GetItems(c.Player.Updater)
	d := itemsColl.Get(args.Key)
	if d == nil {
		return errors.ErrDataNotExists
	}
	if d.Value < int64(args.Num) {
		return errors.ErrItemNotEnough
	}

	goods := config.Data.Goods[d.IID]
	if goods == nil {
		return c.Error("id not exist")
	}
	if goods.Model != config.Data.ItemModel.Chest {
		return c.Error("unable use")
	}
	p := c.Player
	h := Require(goods.Args[0])
	if h == nil {
		return c.Error("unknown use type")
	}
	p.Sub(d.IID, args.Num)
	if ret, err := h(c, args, goods.Args[1:]...); err != nil {
		return err
	} else {
		return ret
	}
}
